package net.sf.midollo.net.httptunnel.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import net.sf.midollo.io.IOStream;

public class HttpTunnelClientIOStream implements IOStream {

  protected final HttpTunnelConnection connection;
  protected boolean connected;

  public HttpTunnelClientIOStream(HttpTunnelConnection connection) throws IOException {
    this.connection = connection;
    this.connected = false;
  }

  public HttpTunnelConnection getConnection() {
    return this.connection;
  }

  public InputStream getInput() throws IOException {
    connect();
    return this.connection.getInputStream();
  }

  public OutputStream getOutput() throws IOException {
    connect();
    return this.connection.getOutputStream();
  }

  public synchronized void close() throws IOException {
    this.connection.disconnect();
    this.connected = false;
  }

  protected synchronized void connect() throws IOException {
    if (!this.connected) {
      this.connection.connect();
      this.connected = true;
    }
  }
}
